﻿namespace BM.Tools.WebControls.MForm.Controls.Helper
{
    using System.Collections.ObjectModel;
    using System.Web.UI;

    /// <summary>
    /// A collection of controls that synchronizes adding controls to the control collection.
    /// </summary>
    /// <typeparam name="T">
    /// The type of the controls
    /// </typeparam>
    public class ControlCollection<T> : Collection<T> where T : Control
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ControlCollection{T}"/> class.
        /// </summary>
        /// <param name="controls">
        /// The controls.
        /// </param>
        public ControlCollection(ControlCollection controls)
        {
            AssociatedControls = controls;
        }

        private ControlCollection AssociatedControls
        {
            get;
            set;
        }

        /// <summary>
        /// Inserts an element into the <see cref="T:System.Collections.ObjectModel.Collection`1"/> at the specified index.
        /// </summary>
        /// <param name="index">
        /// The zero-based index at which item should be inserted.
        /// </param>
        /// <param name="item">
        /// The object to insert. The value can be null for reference types.
        /// </param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// index is less than zero.-or-index is greater than <see cref="P:System.Collections.ObjectModel.Collection`1.Count"/>.
        /// </exception>
        protected override void InsertItem(int index, T item)
        {
            base.InsertItem(index, item);
            AssociatedControls.Add(item);
        }

        /// <summary>
        /// Removes the element at the specified index of the <see cref="T:System.Collections.ObjectModel.Collection`1"/>.
        /// </summary>
        /// <param name="index">
        /// The zero-based index of the element to remove.
        /// </param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// index is less than zero.-or-index is equal to or greater than <see cref="P:System.Collections.ObjectModel.Collection`1.Count"/>.
        /// </exception>
        protected override void RemoveItem(int index)
        {
            var control = this[index];
            base.RemoveItem(index);
            if (AssociatedControls.Contains(control))
            {
                AssociatedControls.Remove(control);
            }
        }
    }
}
